import type { PluginLifecycle, PluginContext } from '@bai-hu/plugin-sdk'
import React, { useEffect, useState } from 'react'

type ThemePayload = { theme: 'light' | 'dark' }

const View: React.FC<{ message?: string; theme?: 'light' | 'dark'; lastTick?: number }> = ({ message, theme = 'light', lastTick }) => {
  return (
    <div className="p-2 rounded border" style={{ background: 'var(--plugin-bg)', color: 'var(--plugin-fg)' }}>
      <span className="font-semibold">Hello World Plugin</span>
      {message ? <p className="opacity-80">{message}</p> : null}
      <div className="text-xs mt-1">theme: {theme}</div>
      {typeof lastTick === 'number' && <div className="text-xs mt-1">last tick from data-panel: {lastTick}</div>}
    </div>
  )
}

export const activate: PluginLifecycle<any, any, React.FC>['activate'] = async (
  ctx: PluginContext,
) => {
  const message = (ctx.manifest as any).config?.message
  ctx.logger.info('hello-world frontend activated', ctx.manifest.name, message)

  return () => {
    const [theme, setTheme] = useState<'light' | 'dark'>('light')
    const [lastTick, setLastTick] = useState<number | undefined>(undefined)
    useEffect(() => {
      const off1 = ctx.events.on('theme:change' as any, (p: ThemePayload) => setTheme(p.theme))
      const off2 = ctx.events.on('data:tick' as any, (p: any) => setLastTick(p.tick))
      return () => { off1(); off2() }
    }, [])
    return <View message={message} theme={theme} lastTick={lastTick} />
  }
}

